"""数据同步相关的序列化器

定义数据同步相关的序列化器，用于API数据的序列化和反序列化。
"""

from rest_framework import serializers
from django.contrib.auth import get_user_model
from .sync_models import SyncSession, SyncItem, ConflictResolution
from .models import Note, Folder
from .serializers import NoteSerializer, FolderSerializer
from django.utils.text import slugify

User = get_user_model()


class FrontendCategorySerializer(serializers.Serializer):
    """前端分类数据序列化器
    
    处理前端发送的分类数据格式，映射到后端Category模型。
    """
    
    id = serializers.IntegerField(required=False, allow_null=True)
    name = serializers.CharField(max_length=100)
    count = serializers.IntegerField(required=False, default=0)
    isDefault = serializers.BooleanField(required=False, default=False)
    parentId = serializers.IntegerField(required=False, allow_null=True)
    
    def to_internal_value(self, data):
        """将前端数据转换为后端格式
        
        前端字段映射：
        - id -> id (保持不变，但转为UUID)
        - name -> name
        - parentId -> parent
        - isDefault -> 添加到元数据中
        - count -> 忽略（动态计算）
        """
        validated_data = super().to_internal_value(data)
        
        # 转换字段名
        internal_data = {
            'name': validated_data['name'],
            'description': f"{'默认分类' if validated_data.get('isDefault', False) else '用户分类'}",
            'color': '#007bff',  # 默认颜色
        }
        
        # 处理父分类ID
        if validated_data.get('parentId'):
            internal_data['parent_id'] = validated_data['parentId']
        
        # 保存原始ID用于映射
        if validated_data.get('id'):
            internal_data['frontend_id'] = validated_data['id']
            
        # 保存是否为默认分类的标记
        internal_data['is_default'] = validated_data.get('isDefault', False)
        
        return internal_data


class FrontendNoteSerializer(serializers.Serializer):
    """前端笔记数据序列化器
    
    处理前端发送的笔记数据格式，映射到后端Note模型。
    """
    
    id = serializers.IntegerField(required=False, allow_null=True)
    title = serializers.CharField(max_length=200)
    content = serializers.CharField()
    folderId = serializers.IntegerField(required=False, allow_null=True)
    createdAt = serializers.CharField(required=False)  # 前端发送的是字符串格式
    updatedAt = serializers.CharField(required=False)  # 前端发送的是字符串格式
    
    def to_internal_value(self, data):
        """将前端数据转换为后端格式
        
        前端字段映射：
        - id -> id (保持不变，但转为UUID)
        - title -> title
        - content -> content
        - folderId -> category (映射到分类)
        - createdAt -> created_at (需要解析时间格式)
        - updatedAt -> updated_at (需要解析时间格式)
        """
        validated_data = super().to_internal_value(data)
        
        # 转换字段名
        internal_data = {
            'title': validated_data['title'],
            'content': validated_data['content'],
            'status': 'draft',  # 默认状态
        }
        
        # 处理分类ID（folderId -> category）
        if validated_data.get('folderId'):
            internal_data['category_id'] = validated_data['folderId']
        
        # 保存原始ID用于映射
        if validated_data.get('id'):
            internal_data['frontend_id'] = validated_data['id']
            
        # 处理时间字段（前端发送的格式需要解析）
        if validated_data.get('createdAt'):
            internal_data['frontend_created_at'] = validated_data['createdAt']
        if validated_data.get('updatedAt'):
            internal_data['frontend_updated_at'] = validated_data['updatedAt']
        
        return internal_data


class SyncSessionSerializer(serializers.ModelSerializer):
    """同步会话序列化器
    
    用于序列化同步会话信息。
    """
    
    duration = serializers.DurationField(read_only=True)
    
    class Meta:
        model = SyncSession
        fields = [
            'id', 'user', 'status', 'client_version', 'device_id',
            'items_uploaded', 'items_downloaded', 'conflicts_detected',
            'conflicts_resolved', 'error_message', 'started_at',
            'completed_at', 'duration'
        ]
        read_only_fields = [
            'id', 'user', 'items_uploaded', 'items_downloaded',
            'conflicts_detected', 'conflicts_resolved', 'started_at',
            'completed_at', 'duration'
        ]
    
    def create(self, validated_data):
        """创建同步会话"""
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class SyncItemSerializer(serializers.ModelSerializer):
    """同步项目序列化器
    
    用于序列化同步项目信息。
    """
    
    has_conflict = serializers.BooleanField(read_only=True)
    
    class Meta:
        model = SyncItem
        fields = [
            'id', 'session', 'item_type', 'item_id', 'action', 'status',
            'client_data', 'server_data', 'client_version', 'server_version',
            'client_timestamp', 'server_timestamp', 'error_message',
            'has_conflict', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'server_data', 'server_version', 'server_timestamp',
            'has_conflict', 'created_at', 'updated_at'
        ]


class ConflictResolutionSerializer(serializers.ModelSerializer):
    """冲突解决序列化器
    
    用于序列化冲突解决信息。
    """
    
    sync_item_detail = SyncItemSerializer(source='sync_item', read_only=True)
    
    class Meta:
        model = ConflictResolution
        fields = [
            'id', 'sync_item', 'sync_item_detail', 'resolution_strategy',
            'resolved_data', 'resolved_by', 'resolution_notes', 'resolved_at'
        ]
        read_only_fields = ['id', 'resolved_by', 'resolved_at']
    
    def create(self, validated_data):
        """创建冲突解决方案"""
        validated_data['resolved_by'] = self.context['request'].user
        return super().create(validated_data)


class SyncRequestSerializer(serializers.Serializer):
    """同步请求序列化器
    
    用于处理客户端的同步请求。
    """
    
    client_version = serializers.CharField(
        max_length=50,
        required=False,
        help_text='客户端版本'
    )
    
    device_id = serializers.CharField(
        max_length=100,
        required=False,
        help_text='设备ID'
    )
    
    last_sync_time = serializers.DateTimeField(
        required=False,
        allow_null=True,
        help_text='上次同步时间'
    )
    
    notes = serializers.ListField(
        child=FrontendNoteSerializer(),
        required=False,
        default=list,
        help_text='笔记数据'
    )
    
    categories = serializers.ListField(
        child=FrontendCategorySerializer(),
        required=False,
        default=list,
        help_text='分类数据'
    )
    
    tags = serializers.ListField(
        child=serializers.DictField(),
        required=False,
        default=list,
        help_text='标签数据'
    )


class SyncResponseSerializer(serializers.Serializer):
    """同步响应序列化器
    
    用于返回同步结果。
    """
    
    session_id = serializers.UUIDField(
        help_text='同步会话ID'
    )
    
    status = serializers.CharField(
        help_text='同步状态'
    )
    
    sync_time = serializers.DateTimeField(
        help_text='同步时间'
    )
    
    notes = serializers.ListField(
        child=NoteSerializer(),
        required=False,
        default=list,
        help_text='服务器端笔记数据'
    )
    
    categories = serializers.ListField(
        child=CategorySerializer(),
        required=False,
        default=list,
        help_text='服务器端分类数据'
    )
    
    tags = serializers.ListField(
        child=TagSerializer(),
        required=False,
        default=list,
        help_text='服务器端标签数据'
    )
    
    conflicts = serializers.ListField(
        child=SyncItemSerializer(),
        required=False,
        default=list,
        help_text='冲突项目'
    )
    
    items_uploaded = serializers.IntegerField(
        help_text='上传项目数'
    )
    
    items_downloaded = serializers.IntegerField(
        help_text='下载项目数'
    )
    
    conflicts_detected = serializers.IntegerField(
        help_text='检测到的冲突数'
    )


class ItemSyncSerializer(serializers.Serializer):
    """项目同步序列化器
    
    用于处理单个项目的同步。
    """
    
    item_type = serializers.ChoiceField(
        choices=['note', 'category', 'tag'],
        help_text='项目类型'
    )
    
    item_id = serializers.CharField(
        max_length=100,
        help_text='项目ID'
    )
    
    action = serializers.ChoiceField(
        choices=['create', 'update', 'delete'],
        help_text='操作类型'
    )
    
    data = serializers.DictField(
        required=False,
        help_text='项目数据'
    )
    
    version = serializers.IntegerField(
        default=1,
        help_text='数据版本'
    )
    
    timestamp = serializers.DateTimeField(
        help_text='时间戳'
    )
    
    def validate(self, attrs):
        """验证同步数据"""
        item_type = attrs['item_type']
        action = attrs['action']
        data = attrs.get('data')
        
        # 创建和更新操作需要数据
        if action in ['create', 'update'] and not data:
            raise serializers.ValidationError(f'{action} 操作需要提供数据')
        
        # 验证数据格式
        if data:
            try:
                if item_type == 'note':
                    NoteSerializer(data=data)
                elif item_type == 'category':
                    CategorySerializer(data=data)
                elif item_type == 'tag':
                    TagSerializer(data=data)
            except Exception as e:
                raise serializers.ValidationError(f'数据格式错误: {str(e)}')
        
        return attrs


class ConflictItemSerializer(serializers.Serializer):
    """冲突项目序列化器
    
    用于表示冲突的项目信息。
    """
    
    item_type = serializers.CharField(help_text='项目类型')
    item_id = serializers.CharField(help_text='项目ID')
    client_data = serializers.DictField(help_text='客户端数据')
    server_data = serializers.DictField(help_text='服务器数据')
    client_timestamp = serializers.DateTimeField(help_text='客户端时间戳')
    server_timestamp = serializers.DateTimeField(help_text='服务器时间戳')
    conflict_reason = serializers.CharField(help_text='冲突原因')